# core/cache_manager.py - 简化版本
import json
import threading
from pathlib import Path
from typing import List, Dict, Any

class CacheManager:
    """智能缓存管理器 - 简化版本"""
    
    def __init__(self, config, download_manager):
        self.config = config
        self.download_manager = download_manager
        self.cache_dir = config.download_cache_dir
        
        # 确保缓存目录存在
        self.cache_dir.mkdir(parents=True, exist_ok=True)
    
    def preload_all_packages(self, file_list):
        """预加载所有包数据 - 简化版本"""
        def preload_task():
            try:
                for file_info in file_list:
                    package_name = file_info.name
                    self._cache_single_package(package_name)
            except Exception as e:
                print(f"预加载失败: {str(e)}")
        
        # 在后台线程中执行预加载
        threading.Thread(target=preload_task, daemon=True).start()
    
    def _cache_single_package(self, package_name: str):
        """缓存单个包"""
        try:
            package_cache_dir = self.cache_dir / package_name
            package_cache_dir.mkdir(exist_ok=True)
            
            # 只下载info.json，图片可以稍后按需加载
            remote_info_path = f"{self.config.data_dir}/{self.config.downloadfiles_dir}/{package_name}/info.json"
            local_info_path = package_cache_dir / "info.json"
            
            if not local_info_path.exists():
                if hasattr(self.download_manager, 'cloud_sync') and self.download_manager.cloud_sync:
                    self.download_manager.cloud_sync.download_file(
                        remote_info_path, str(local_info_path)
                    )
        except Exception as e:
            print(f"缓存包 {package_name} 失败: {str(e)}")
    
    def get_cached_info(self, package_name: str) -> Dict[str, Any]:
        """获取缓存的info.json"""
        cache_file = self.cache_dir / package_name / "info.json"
        if cache_file.exists():
            try:
                with open(cache_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception:
                pass
        return None
    
    def get_cached_image_path(self, package_name: str) -> Path:
        """获取缓存的预览图路径"""
        cache_file = self.cache_dir / package_name / "preview.png"
        if cache_file.exists():
            return cache_file
        return None
    
    def clear_all_cache(self):
        """清除所有缓存"""
        import shutil
        if self.cache_dir.exists():
            shutil.rmtree(self.cache_dir)
        self.cache_dir.mkdir(parents=True, exist_ok=True)